//
//  YRJRecommendViewController.m
//  TravelAroundTheWorld
//
//  Created by dllo on 15/10/22.
//  Copyright (c) 2015年 yanrenjie. All rights reserved.
//

#import "YRJRecommendViewController.h"
#import "YRJTripHeader.h"
#import <Reachability.h>


@interface YRJRecommendViewController ()<UIScrollViewDelegate, UITableViewDataSource, UITableViewDelegate, YRJDiscountZoneTableViewCellDelegate>
@property(nonatomic, retain)UITableView *tableView;
@property(nonatomic, retain)UIScrollView *scrollView;
//@property(nonatomic, retain)UIPageControl *pageControl; // 轮播图上的点
@property(nonatomic, retain)NSMutableArray *scrollArr;
@property(nonatomic, retain)MBProgressHUD *hud;
@property(nonatomic, retain)NSMutableArray *findNextStationArr;
@property(nonatomic, retain)NSMutableArray *grabSpecialsArr;   // 抢特价折扣
@property(nonatomic, retain)NSMutableArray *hotAttractionsArr; // 热门游记数据
@property(nonatomic, retain)NSMutableArray *discountSubjectArr; // 抢特价折扣的主题图片, 最上面的那一张横向的大图片
@end


NSInteger pageIndex = 0;
@implementation YRJRecommendViewController
- (void)dealloc {
    [_tableView release];
    [_scrollView release];
//    [_pageControl release];
    [_scrollArr release];
    [_hud release];
    [_findNextStationArr release];
    [_grabSpecialsArr release];
    [_hotAttractionsArr release];
    [_discountSubjectArr release];
    
    [super dealloc];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    self.automaticallyAdjustsScrollViewInsets = YES;
    self.title = @"推荐";
    self.tabBarController.hidesBottomBarWhenPushed = YES;
    // 修改导航栏的背景颜色
    self.navigationController.navigationBar.barTintColor = [UIColor colorWithRed:70 / 255.0 green:190 / 255.0 blue:200 / 255.0 alpha:1];
    
    // 在所搜栏右边添加一个与我相关的"我的"按钮
    self.navigationItem.rightBarButtonItem = [[[UIBarButtonItem alloc] initWithTitle:@"搜索" style:UIBarButtonItemStylePlain target:self action:@selector(searchAction:)] autorelease];
    self.navigationController.navigationBar.translucent = NO;
    
    
    // 创建tableView
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT - 64) style:UITableViewStyleGrouped];
    self.tableView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.tableView];
    [_tableView release];
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    
    self.tableView.header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(pullDownToRefresh)];
    
    self.tableView.footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        pageIndex++;
        [self pullUpToLoading];
    }];
    
    self.hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    self.hud.labelText = @"Loading...";
#pragma mark - 判断是否有网络,如果有网, 直接从网上获取数据, 如果没有网络, 就从本地的文件中读取数据
    if ([self isConnectionAvailable]) {
        // 请求热门游记的数据
        //    [self createHotAttractionsData];
        [self createScrollData];
        // 推荐页的轮播图, 以及控制轮播图的页数的点
        [self createScrollView];
    } else {
        if (![self isHaveFolder]) {
            NSLog(@"无文件");
        } else {
            NSLog(@"没有网络");
            [self createScrollView];
            
            NSString *sandBoxPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
            NSString *cachePath = [sandBoxPath stringByAppendingPathComponent:@"recommend.plist"];
            NSDictionary *scrollDic = [NSKeyedUnarchiver unarchiveObjectWithFile:cachePath];
            
            NSArray *arr1 = scrollDic[@"data"][@"slide"];
            NSArray *arr2 = scrollDic[@"data"][@"subject"];
            NSArray *arr3 = scrollDic[@"data"][@"discount"];
            
            // 将解析好的数据放到对象中
            self.scrollArr = [YRJScrollImageInfoModel baseModelByArr:arr1];
            self.findNextStationArr = [YRJFindNextStationModel baseModelByArr:arr2];
            self.grabSpecialsArr = [YRJDiscountZoneModel baseModelByArr:arr3];
            
            
            
            if (self.scrollArr.count > 0 && self.findNextStationArr.count > 0 && self.grabSpecialsArr.count > 0) {
                // 设置轮播图的滚动范围
                self.scrollView.contentSize = CGSizeMake((self.scrollArr.count + 1) * SWIDTH, 0);
                // 将数据放到轮播图中
                for (NSInteger i = 0; i < self.scrollArr.count; i++) {
                    UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(SWIDTH * i, 0, SWIDTH, (200.0 / 667) * SHEIGHT)];
                    [imageView sd_setImageWithURL:[NSURL URLWithString:[self.scrollArr[i] photo]] placeholderImage:[UIImage imageNamed:@"placeHold.png"]];
                    [self.scrollView addSubview:imageView];
                    imageView.tag = 2000 + i;
                    // 给轮播图添加一个手势, 打开用户交互
                    [imageView setUserInteractionEnabled:YES];
                    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAction:)];
                    [imageView addGestureRecognizer:tap];
                    [tap release];
                    [imageView release];   // 注意在后面要用的对象不能提前释放, 一定要在使用完之后才能释放
                }
                
                // 设置最后一个图片, 让轮播图播放流畅
                UIImageView *lastImageView = [[UIImageView alloc] initWithFrame:CGRectMake(SWIDTH * self.scrollArr.count, 0, SWIDTH, (200.0 / 667) * SHEIGHT)];
                [lastImageView sd_setImageWithURL:[NSURL URLWithString:[self.scrollArr[0] photo]] placeholderImage:[UIImage imageNamed:@"placeHold.png"]];
                lastImageView.tag = 2000;
                [lastImageView setUserInteractionEnabled:YES];
                [self.scrollView addSubview:lastImageView];
                [lastImageView release];
                //            [self createPageControl];
                
                // 反归档看热门游记
                NSString *cachePathHotPlace = [sandBoxPath stringByAppendingPathComponent:@"hotPlace.plist"];
                NSDictionary *dic = [NSKeyedUnarchiver unarchiveObjectWithFile:cachePathHotPlace];
                self.hotAttractionsArr = [YRJHotAttractionsModel baseModelByArr:dic[@"data"]];
                [self.tableView reloadData];
            }
            self.hud.hidden = YES;
        }
    }

}

#pragma mark - 点击跳到搜索页面
- (void)searchAction:(UIButton *)button {
    YRJSearchViewController *searchVC = [[YRJSearchViewController alloc] init];
    self.tabBarController.tabBar.hidden = YES;
    [self.navigationController pushViewController:searchVC animated:YES];
    [searchVC release];
}


#pragma mark 实现上拉加载, 下拉刷新功能
- (void)pullUpToLoading {
    NSString *strURL = [NSString stringWithFormat:@"%@%ld%@", @"http://open.qyer.com/qyer/recommands/trip?client_id=qyer_ios&client_secret=cd254439208ab658ddf9&count=10&page=", (long)pageIndex, @"&track_app_channel=App%2520Store&track_app_version=6.7&track_device_info=iPhone%25204%28ChinaMobile%2CChinaUnicom%29&track_deviceid=AB5B28ED-8670-4190-873A-F09EFE3EB3E8&track_os=ios%25207.1.2&type=index&v=1"];
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    [manager GET:strURL parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSDictionary *dic = responseObject;
        NSArray *tempArr = [YRJHotAttractionsModel baseModelByArr:dic[@"data"]];
        
        for (YRJHotAttractionsModel *tempModel in tempArr) {
            [self.hotAttractionsArr addObject:tempModel];
        }
        
        [self.tableView reloadData];
        [self.tableView.header endRefreshing];
        [self.tableView.footer endRefreshing];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
    }];
}

- (void)pullDownToRefresh {
    [self.hotAttractionsArr removeAllObjects];
    [self pullUpToLoading];
}

#pragma mark 普通方法, 创建轮播图scrollView, 轮播图的点pageControl
- (void)createScrollView {
    // 创建scrollView
    self.scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, (220.0 / 667.0) * SHEIGHT)];
    self.scrollView.backgroundColor = [UIColor whiteColor];
    self.tableView.tableHeaderView = self.scrollView;
    [_scrollView release];
    self.scrollView.showsHorizontalScrollIndicator = NO;
    self.scrollView.pagingEnabled = YES;
    // 设置代理人
    self.scrollView.delegate = self;
    // 请求首页除了热门游记之外的数据
    // 设置一个定时器, 让图片定时切换
    [NSTimer scheduledTimerWithTimeInterval:5 target:self selector:@selector(changePicture) userInfo:nil repeats:YES];
}

//- (void)createPageControl {
//    // 创建一个pageControl
//    self.pageControl = [[UIPageControl alloc] initWithFrame:CGRectMake(0, (160.0 / 375.0) * SWIDTH, SWIDTH, (50.0 / 667) * SHEIGHT)];
//    self.pageControl.backgroundColor = [UIColor clearColor];
//    [self.tableView addSubview:self.pageControl];
//    // 设置当前pageControl 的点的个数
//    self.pageControl.numberOfPages = self.scrollArr.count;
//    // 没有被点击的点的颜色
//    self.pageControl.pageIndicatorTintColor = [UIColor clearColor];
//    // 当前点的颜色
//    self.pageControl.currentPageIndicatorTintColor = [UIColor clearColor];
//    //
//    [self.pageControl addTarget:self action:@selector(pageControlAction:) forControlEvents:UIControlEventValueChanged];
//    [_pageControl release];
//    // 想要scrollView实现缩放功能, 需要先设置最大最小的缩放比例
//    self.scrollView.minimumZoomScale = 0.1;
//    self.scrollView.maximumZoomScale = 3;
//}

// 控制点的位置和当前图片的张数一致
//- (void)pageControlAction:(UIPageControl *)page {
//    [self.scrollView setContentOffset:CGPointMake((page.currentPage + 1) * WIDTH, 0) animated:YES];
//}

// 轮播图获取数据方法实现
- (void)createScrollData {
    NSString *strURLOne = @"http://open.qyer.com/qyer/recommands/entry?client_id=qyer_ios&client_secret=cd254439208ab658ddf9&count=20&page=1&track_app_channel=App%2520Store&track_app_version=6.7&track_device_info=iPhone%25204%28ChinaMobile%2CChinaUnicom%29&track_deviceid=AB5B28ED-8670-4190-873A-F09EFE3EB3E8&track_os=ios%25207.1.2&v=1";
    // 创建URL
    NSURL *url = [NSURL URLWithString:strURLOne];
    // 创建request
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    // 创建连接
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        // JSON 解析
        NSDictionary *scrollDic = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
        NSArray *arr1 = scrollDic[@"data"][@"slide"];
        NSArray *arr2 = scrollDic[@"data"][@"subject"];
        NSArray *arr3 = scrollDic[@"data"][@"discount"];
        // 将解析好的数据放到对象中
        self.scrollArr = [YRJScrollImageInfoModel baseModelByArr:arr1];
        self.findNextStationArr = [YRJFindNextStationModel baseModelByArr:arr2];
        self.grabSpecialsArr = [YRJDiscountZoneModel baseModelByArr:arr3];
        
#warning 在此进行缓存处理, 直接将解析后的整个数据写入到本地文件中
        // 1. 找到沙盒路径
        NSString *sandBoxPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
        NSString *cachePath = [sandBoxPath stringByAppendingPathComponent:@"recommend.plist"];
        // 归档
        [NSKeyedArchiver archiveRootObject:scrollDic toFile:cachePath];
        NSLog(@"----%@", cachePath);
        
        // 设置轮播图的滚动范围
        self.scrollView.contentSize = CGSizeMake((self.scrollArr.count + 1) * SWIDTH, 0);
        
        // 将数据放到轮播图中
        for (NSInteger i = 0; i < self.scrollArr.count; i++) {
            UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(SWIDTH * i, 0, SWIDTH, (200.0 / 667) * SHEIGHT)];
            [imageView sd_setImageWithURL:[NSURL URLWithString:[self.scrollArr[i] photo]] placeholderImage:[UIImage imageNamed:@"placeHold.png"]];
            [self.scrollView addSubview:imageView];
            [imageView release];
            imageView.tag = 2000 + i;
            // 给轮播图添加一个手势
            [imageView setUserInteractionEnabled:YES];
            UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAction:)];
            [imageView addGestureRecognizer:tap];
            [tap release];
            
        }
        
        // 设置最后一个图片, 让轮播图播放流畅
        UIImageView *lastImageView = [[UIImageView alloc] initWithFrame:CGRectMake(SWIDTH * self.scrollArr.count, 0, SWIDTH, (200.0 / 667) * SHEIGHT)];
        [lastImageView sd_setImageWithURL:[NSURL URLWithString:[self.scrollArr[0] photo]] placeholderImage:[UIImage imageNamed:@"placeHold.png"]];
        lastImageView.tag = 2000;
        [lastImageView setUserInteractionEnabled:YES];
        [self.scrollView addSubview:lastImageView];
        [lastImageView release];
//        [self createPageControl];
        [self.tableView reloadData];
        self.hud.hidden = YES;
    }];
    
    
    NSString *strURLTwo = [NSString stringWithFormat:@"%@%ld%@", @"http://open.qyer.com/qyer/recommands/trip?client_id=qyer_ios&client_secret=cd254439208ab658ddf9&count=10&page=", (long)pageIndex, @"&track_app_channel=App%2520Store&track_app_version=6.7&track_device_info=iPhone%25204%28ChinaMobile%2CChinaUnicom%29&track_deviceid=AB5B28ED-8670-4190-873A-F09EFE3EB3E8&track_os=ios%25207.1.2&type=index&v=1"];
    NSLog(@"%@", strURLTwo);
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    [manager GET:strURLTwo parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSDictionary *dic = responseObject;
#warning 再次进行缓存处理
        // 1. 找到沙盒路径
        NSString *sandBoxPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
        NSString *cachePath = [sandBoxPath stringByAppendingPathComponent:@"hotPlace.plist"];
        // 归档
        [NSKeyedArchiver archiveRootObject:dic toFile:cachePath];
        self.hotAttractionsArr = [YRJHotAttractionsModel baseModelByArr:dic[@"data"]];
        [self.tableView reloadData];
        pageIndex++;
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
    }];
}


#pragma mark - 轮播图相关方法
// 轮播图定时切换
- (void)changePicture {
    [self.scrollView setContentOffset:CGPointMake(self.scrollView.contentOffset.x + SWIDTH, 0) animated:YES];
    // 判断是否到当前的最后一张, 如果到了, 需要把偏移量设置到第一张图片的位置
    if (self.scrollView.contentOffset.x == self.scrollArr.count * SWIDTH) {
        self.scrollView.contentOffset = CGPointMake(0, 0);
//        self.pageControl.currentPage = self.scrollView.contentOffset.x / SWIDTH;
    } else {
//        self.pageControl.currentPage = self.scrollView.contentOffset.x / SWIDTH;
    }
   
}


// 轮播图轻点方法
- (void)tapAction:(UITapGestureRecognizer *)tap {
    YRJTapScrollImageWebViewController *tapScrollVC = [[YRJTapScrollImageWebViewController alloc] init];
    YRJScrollImageInfoModel *tempModel = self.scrollArr[tap.view.tag - 2000];
    tapScrollVC.string = tempModel.url;
    self.tabBarController.tabBar.hidden = YES;
    [self.navigationController pushViewController:tapScrollVC animated:YES];
    
    
}


// 热门游记数据
- (void)createHotAttractionsData {
    NSString *strURL = [NSString stringWithFormat:@"%@%ld%@", @"http://open.qyer.com/qyer/recommands/trip?client_id=qyer_ios&client_secret=cd254439208ab658ddf9&count=10&page=", (long)pageIndex, @"&track_app_channel=App%2520Store&track_app_version=6.7&track_device_info=iPhone%25204%28ChinaMobile%2CChinaUnicom%29&track_deviceid=AB5B28ED-8670-4190-873A-F09EFE3EB3E8&track_os=ios%25207.1.2&type=index&v=1"];
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    [manager GET:strURL parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSDictionary *dic = responseObject;
        self.hotAttractionsArr = [YRJHotAttractionsModel baseModelByArr:dic[@"data"]];
        [self.tableView reloadData];
        pageIndex++;
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
    }];

}


#pragma mark tableView 的协议方法
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 3;
}

// 设置每个分区的标题
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
    if (section == 0) {
        return @"发现下一站";
    } else if (section == 1) {
        return @"折扣你先抢";
    } else {
        return @"看热门游记";
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        return (230.0 / 667) * SHEIGHT;
    } else if (indexPath.section == 1) {
        return (360.0 / 667) * SHEIGHT;
    } else {
        return (125.0 / 667) * SHEIGHT;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return (40.0 / 667) * HEIGHT;
}

// cell 点击触发实现方法
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    YRJHotAttractionsDetailViewController *hotAttractionsDetailVC = [[YRJHotAttractionsDetailViewController alloc] init];
    self.tabBarController.tabBar.hidden = YES;
    [self.navigationController pushViewController:hotAttractionsDetailVC animated:YES];
    hotAttractionsDetailVC.string = [self.hotAttractionsArr[indexPath.row] view_url];
    [hotAttractionsDetailVC release];

}
#pragma mark 两个必须实现的tableView的协议方法
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section == 0) {
        return 1;
    } else if (section == 1) {
        return 1;
    } else {
        self.tableView.separatorStyle = YES;
        return self.hotAttractionsArr.count;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        static NSString *nextStationReuse = @"nextStationReuse";
        YRJFindNextStationViewCell *cell = [tableView dequeueReusableCellWithIdentifier:nextStationReuse];
        if (!cell) {
            cell = [[[YRJFindNextStationViewCell alloc] initWithStyle:0 reuseIdentifier:nextStationReuse] autorelease];
        }
        if (self.findNextStationArr.count != 0) {
            [cell.leftImageView sd_setImageWithURL:[NSURL URLWithString:[self.findNextStationArr[0] photo]] placeholderImage:[UIImage imageNamed:@"placeHold.png"]];
            [cell.upImageView sd_setImageWithURL:[NSURL URLWithString:[self.findNextStationArr[1] photo]] placeholderImage:[UIImage imageNamed:@"placeHold.png"]];
            [cell.downImageView sd_setImageWithURL:[NSURL URLWithString:[self.findNextStationArr[2] photo]] placeholderImage:[UIImage imageNamed:@"placeHold.png"]];   
        }
        return cell;
    } else if (indexPath.section == 1) {
        static NSString *discountReuse = @"discountReuse";
        YRJDiscountZoneTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:discountReuse];
        if (!cell) {
            cell = [[[YRJDiscountZoneTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:discountReuse] autorelease];
        }
        // 签订跳转协议
        cell.delegate = self;
        cell.tempArray = self.grabSpecialsArr;
        return cell;
    } else {
        static NSString *hotAttractionsReuse = @"hotAttractionsReuse";
        YRJHotAttractionsTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:hotAttractionsReuse];
        if (!cell) {
            cell = [[[YRJHotAttractionsTableViewCell alloc] initWithStyle:0 reuseIdentifier:hotAttractionsReuse] autorelease];
        }
        if (self.hotAttractionsArr.count != 0) {
            [cell.photoImageView sd_setImageWithURL:[NSURL URLWithString:[self.hotAttractionsArr[indexPath.row] photo]] placeholderImage:[UIImage imageNamed:@"placeHold.png"]];
            cell.titleLabel.text = [self.hotAttractionsArr[indexPath.row] title];
            cell.viewsLabel.text = [NSString stringWithFormat:@"%@%@%@", @"浏览(", [[self.hotAttractionsArr[indexPath.row] views] stringValue], @")"];
            cell.replysLabel.text = [NSString stringWithFormat:@"%@%@%@", @"评论(", [self.hotAttractionsArr[indexPath.row] replys], @")"];
        }
        return cell;
    }
}

#pragma mark - cell中的按钮触发实现方法
// 发现下一站的查看全部实现
- (void)forAllFindNextStationAction:(UIButton *)button {
    YRJFindNextStationForAllViewController *findNextStationForAllVC = [[YRJFindNextStationForAllViewController alloc] init];
    self.tabBarController.tabBar.hidden = YES;
    [self.navigationController pushViewController:findNextStationForAllVC animated:YES];
    [findNextStationForAllVC release];
}

#pragma mark - 在折扣你先抢的右边添加一个查看全部的按钮
//- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
//    if (section == 1) {
//        UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
//        button.backgroundColor = [UIColor whiteColor];
//        button.frame = CGRectMake(0, 0, (365.0 / 375) * WIDTH, (20.0 / 667) * HEIGHT);
//        [button setTitle:@"查看全部" forState:UIControlStateNormal];
//        [button addTarget:self action:@selector(forAllDiscountZoneAction:) forControlEvents:UIControlEventTouchUpInside];
//        return button;
//    } else {
//        return nil;
//    }
//}

#pragma mark - 查看全部的按钮
// 给分区返回一个View头部
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    UIView *headView = [[[UIView alloc] initWithFrame:CGRectMake((5.0 / 375) * WIDTH, 0, (365.0 / 375) * WIDTH, (40.0 / 667) * HEIGHT)] autorelease];
    headView.backgroundColor = [UIColor whiteColor];
    UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake((20.0 / 375) * WIDTH, (5.0 / 667) * HEIGHT, (100.0 / 375) * WIDTH, (30.0 / 667) * HEIGHT)];
    [headView addSubview:titleLabel];
    if (section == 0) {
        titleLabel.text = @"发现下一站";
        UIButton *forMoreButton = [UIButton buttonWithType:UIButtonTypeSystem];
        forMoreButton.frame = CGRectMake((265.0 / 375) * WIDTH, (5.0 / 667) * HEIGHT, (100.0 / 375) * WIDTH, (30.0 / 667) * HEIGHT);
        [headView addSubview:forMoreButton];
        [forMoreButton setTitle:@"查看全部 〉" forState:UIControlStateNormal];
        [forMoreButton setTintColor:[UIColor greenColor]];
        [forMoreButton addTarget:self action:@selector(forAllFindNextStationAction:) forControlEvents:UIControlEventTouchUpInside];
    } else if (section == 1) {
        titleLabel.text = @"折扣你先抢";
        UIButton *forMoreButton = [UIButton buttonWithType:UIButtonTypeSystem];
        forMoreButton.frame = CGRectMake((265.0 / 375) * WIDTH, (5.0 / 667) * HEIGHT, (100.0 / 375) * WIDTH, (30.0 / 667) * HEIGHT);
        [headView addSubview:forMoreButton];
        [forMoreButton setTitle:@"查看全部 〉" forState:UIControlStateNormal];
        [forMoreButton setTintColor:[UIColor greenColor]];
        [forMoreButton addTarget:self action:@selector(forAllDiscountZoneAction:) forControlEvents:UIControlEventTouchUpInside];
    } else {
        titleLabel.text = @"看热门游记";
    }
    [titleLabel release];
//    UIButton *forMoreButton = [UIButton buttonWithType:UIButtonTypeSystem];
//    forMoreButton.frame = CGRectMake((265.0 / 375) * WIDTH, (5.0 / 667) * HEIGHT, (100.0 / 375) * WIDTH, (30.0 / 667) * HEIGHT);
//    [forMoreButton setTitle:@"查看全部 〉" forState:UIControlStateNormal];
//    [forMoreButton setTintColor:[UIColor greenColor]];
//    if (section == 0) {
//        [forMoreButton addTarget:self action:@selector(forAllHotCityAction:) forControlEvents:UIControlEventTouchUpInside];
//    } else {
//        [forMoreButton addTarget:self action:@selector(forTripValuedAction:) forControlEvents:UIControlEventTouchUpInside];
//    }
//    
//    [headView addSubview:forMoreButton];
    return headView;
}




#pragma mark - Method push To Discount Zone Web View
- (void)pushToDiscountZoneWebView:(NSNumber *)id {
    YRJDiscountZoneWebViewController *discountZoneWebVC = [[YRJDiscountZoneWebViewController alloc] init];
    self.tabBarController.tabBar.hidden = YES;
    [self.navigationController pushViewController:discountZoneWebVC animated:YES];
    discountZoneWebVC.id = id;
    [discountZoneWebVC release];
}

- (void)forAllDiscountZoneAction:(UIButton *)button {
    YRJDiscountZoneForAllViewController *discountZoneForAllVC = [[YRJDiscountZoneForAllViewController alloc] init];
    self.tabBarController.tabBar.hidden = YES;
    [self.navigationController pushViewController:discountZoneForAllVC animated:YES];
    [discountZoneForAllVC release];
}


- (void)viewWillAppear:(BOOL)animated {
    self.tabBarController.tabBar.hidden = NO;
    animated = YES;
}

#if 1

#pragma mark - 判断是否有网络
-(BOOL) isConnectionAvailable {
    BOOL isExistenceNetwork = YES;
    Reachability *reach = [Reachability reachabilityWithHostName:@"www.apple.com"];
    switch ([reach currentReachabilityStatus]) {
        case NotReachable:
            isExistenceNetwork = NO;
            //NSLog(@"notReachable");
            break;
        case ReachableViaWiFi:
            isExistenceNetwork = YES;
            //NSLog(@"WIFI");
            break;
        case ReachableViaWWAN:
            isExistenceNetwork = YES;
            //NSLog(@"3G");
            break;
    }
    
    if (!isExistenceNetwork) {
        //        MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];//<span style="font-family: Arial, Helvetica, sans-serif;">MBProgressHUD为第三方库，不需要可以省略或使用AlertView</span>
        //        hud.removeFromSuperViewOnHide =YES;
        //        hud.mode = MBProgressHUDModeText;
        //        hud.labelText = @"当前网络不可用，请检查网络连接";  //提示的内容
        //        hud.minSize = CGSizeMake(132.f, 58.0f);
        //        [hud hide:YES afterDelay:3];
        UIAlertView *alter = [[UIAlertView alloc] initWithTitle:@"温馨提示" message:@"当前无网络" delegate:self cancelButtonTitle:@"确定" otherButtonTitles: nil];
        [alter show];
        [alter release];
        return NO;
    }
    
    return isExistenceNetwork;
}

- (BOOL)isHaveFolder {
    //找路径
    NSString *sandBoxPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
    //拼接
    NSString *itemFile = [sandBoxPath stringByAppendingPathComponent:@"Travel/Activity"];
    //创建管理者
    NSFileManager *manager = [NSFileManager defaultManager];
    // 判断文件夹是否存在
    if (![manager fileExistsAtPath:itemFile]) {
        return YES;
    }
    return NO;
}


#pragma mark - 缓存
- (void)isHaveFileDocument {
    //1.找沙盒路径
    NSString *sandboxpath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
    //2.拼接电影的文件夹
    NSString *movieFile = [sandboxpath stringByAppendingPathComponent:@"Travel"];
    //3.创建一个文件管理者
    NSFileManager *manager = [NSFileManager defaultManager];
    //通过管理者调用方法,根据路径判断文件夹是否存在
    if (![manager fileExistsAtPath:movieFile]) {
        //创建文件夹
        [manager createDirectoryAtPath:movieFile withIntermediateDirectories:YES attributes:nil error:nil];
        
    }
    NSLog(@"%@", movieFile);
}


-(void)isHaveFileActivity {
    //1.找沙盒路径
    NSString *sandboxpath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
    //2.拼接电影的文件夹
    NSString *movieFile = [sandboxpath stringByAppendingPathComponent:@"Travel/Activity"];
    //3.创建一个文件管理者
    NSFileManager *manager = [NSFileManager defaultManager];
    //通过管理者调用方法,根据路径判断文件夹是否存在
    if (![manager fileExistsAtPath:movieFile]) {
        //创建文件夹
        [manager createDirectoryAtPath:movieFile withIntermediateDirectories:YES attributes:nil error:nil];
        
    }
    NSLog(@"%@", movieFile);
}


#endif

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

@end
